package controller;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import persistence.product.ProductDAO;
import persistence.product.ProductPersistFactory;
import persistence.sale.SaleDAO;
import persistence.sale.SalePersistFactory;
import persistence.user.UserDAO;
import persistence.user.UserPersistFactory;

public class StartUpContextListener implements ServletContextListener {

    private ProductDAO productDAO;
    private UserDAO userDAO;
    private SaleDAO saleDAO;

    public void contextInitialized(ServletContextEvent evt) {
        String url, driver, user, password, persistenceMechanism;
        ServletContext context = evt.getServletContext();
        url = context.getInitParameter("databaseURL");
        driver = context.getInitParameter("databaseDriver");
        user = context.getInitParameter("databaseUser");
        password = context.getInitParameter("databasePassword");
        persistenceMechanism = context.getInitParameter("persistenceMechanism");

        productDAO = ProductPersistFactory.getProductDAO(persistenceMechanism);
        userDAO = UserPersistFactory.getUserDAO(persistenceMechanism);
        saleDAO = SalePersistFactory.getSaleDAO(persistenceMechanism);
        boolean ok = productDAO.setUp(url, driver, user, password) &&
                userDAO.setUp(url, driver, user, password) &&
                saleDAO.setUp(url, driver, user, password);
        if (!ok) {
            context.setAttribute("persistenceMechanism", "none");
        }
    }

    public void contextDestroyed(ServletContextEvent evt) {
        boolean ok = productDAO.disconnect() && userDAO.disconnect() && saleDAO.disconnect();
        if (!ok) {
            Logger.getLogger(StartUpContextListener.class.getName()).log(Level.SEVERE,
                    "No se encontro el driver para la base de datos");
        }
    }
}
